<?php
use Dingo\Api\Facade\Route;

/**
 * 判断字符串的类型
 *
 * @return email/mobile/name/other
 */
if (!function_exists('Regular')) {
    function Regular($string)
    {

        $regexs = array(
            'email' => '/^[_.0-9a-z-a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,4}$/',
            'mobile' => '/^0{0,1}1[0-9]{10}$/',
            'id' => '/^\d+$/'
        );

        foreach ($regexs as $key => $val) {
            if (preg_match($val, $string)) {
                return $key;
            }
        }

        return 'name';
    }
}


/*
 * MD5加密
 *
 * @return MD5
 */
if (!function_exists('PMD5')) {
    function PMD5($string, $salt)
    {

        return md5($string . $salt . config('app.key') . md5(config('app.key') . $string . $salt));
    }
}

//去除字符串中的空格 换行 单双引号 逗号
if (!function_exists('CLEAN_STR')) {
    function CLEAN_STR($str)
    {
        $replace = array(" ", "　", "\t", "\n", "\r", "'", "\"", "，", ",");
        $str = str_replace($replace, '', $str);
        // $str=str_replace("，",",",$str);
        // $str=rtrim($str, ",");
        return $str;
    }
}
//只留下数字英文逗号并且出去了最后一个逗号
if (!function_exists('NUM_STR')) {
    function NUM_STR($str)
    {
        $str = str_replace("，", ",", $str);
        $str = preg_replace('/[^\d,]+/', '', $str);
        $str = rtrim($str, ",");
        return $str;
    }
}


//base64加密
if (!function_exists('ENCODE')) {
    function ENCODE($data)
    {
        return str_replace(array('+', '/', '='), array('-', '_', ''), base64_encode(serialize($data)));
    }
}

//对应base64解密
if (!function_exists('DECODE')) {
    function DECODE($string)
    {
        $data = str_replace(array('-', '_'), array('+', '/'), $string);
        $mod4 = strlen($data) % 4;
        ($mod4) && $data .= substr('====', $mod4);
        return unserialize(base64_decode($data));
    }
}


/*
 * 将数组内容中的ID设置为Key
 *
 * @return object
 */
if (!function_exists('getIdArray')) {
    function getIdArray($caches, $key = 'id')
    {

        $caches = json_decode(json_encode($caches), true);

        $array = array();
        foreach ($caches as $k => $v) {
            $array[$v[$key]] = $v;
        }

        return $array;
    }
}


/**
 * 获取当前控制器与方法
 *
 * @return array
 */
if (!function_exists('getCurrentAction')) {
    function getCurrentAction()
    {

        $action = \Route::current()->getActionName();
        list($class, $method) = explode('@', $action);
        $class = substr(strrchr($class, '\\'), 1);

        return ['controller' => $class, 'method' => $method];
    }
}


/**
 * 获取当前控制器名
 *
 * @return string
 */
if (!function_exists('getCurrentControllerName')) {
    function getCurrentControllerName()
    {

        return str_replace('Controller', '', getCurrentAction()['controller']);
    }
}


/**
 * 获取当前方法名
 *
 * @return string
 */
if (!function_exists('getCurrentMethodName')) {
    function getCurrentMethodName()
    {

        return getCurrentAction()['method'];
    }
}


//API返回接口
//if (!function_exists('apiJson')) {
//    function apiJson($data, $msg = '', $extra = [], $code = 0)
//    {
//        $json = [
//            'code' => $code,
//            'message' => $msg,
//            'data' => $data,
//        ];
//        if ($extra) {
//            $json = array_merge($json, $extra);
//        }
//        return $json;
//    }
//}
if (!function_exists('apiJson')) {
    function apiJson($data, $msg = '', $extra = [], $code = 0)
    {
        $json = [
            'code' => $code,
            'message' => $msg,
            'data' => $data,
            'time' => time(),
        ];
        if ($extra) {
            $json = array_merge($json, $extra);
        }
        if (app()->request->input('jwt') && app()->request->input('jwt') == 'refresh') {
            $json = array_merge($json, ['jwt-refresh-access_token' => app()->request->input('access_token')]);
        }
        return $json;
    }
}

//API返回接口的针对错误情况的2次封装
if (!function_exists('apiJsonError')) {
    function apiJsonError($msg, $code = 10001, $data = '', $extra = [])
    {
        return apiJson($data, $msg, $extra, $code);
    }
}

//API返回接口的针对成功提醒的2次封装
if (!function_exists('apiJsonMsg')) {
    function apiJsonMsg($msg, $code = 0, $data = '', $extra = [])
    {
        return apiJson($data, $msg, $extra, $code);
    }
}
//正则：手机号码格式验证
if (!function_exists('check_phone')) {
    function check_phone($str)//电话号码正则表达试
    {
        // return (preg_match("/^(((d{3}))|(d{3}-))?((0d{2,3})|0d{2,3}-)?[1-9]d{6,8}$/", $str)) ? true : false;
        return (preg_match("/^1[345789]\d{9}$/", $str)) ? true : false;

    }
}
//正则：邮箱格式验证
if (!function_exists('check_email')) {
    function check_email($email)
    {
        return (preg_match("/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/", $email)) ? true : false;
    }
}
//正则：域名格式验证
if (!function_exists('check_domain')) {
    function check_domain($domain)
    {
        $regex = '@(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?«»“”‘’]))@';
        return (preg_match($regex, $domain)) ? true : false;
    }
}

/**
 * select返回的数组进行整数映射转换
 *
 */
if (!function_exists('int_to_string')) {
    function int_to_string(&$data, $map = array('status' => array(1 => '正常', -1 => '删除', 0 => '禁用', 2 => '未审核', 3 => '草稿')))
    {
        if ($data === false || $data === null) {
            return $data;
        }
        if (!is_object($data)) {
            $data = (array)$data;
        }
        foreach ($data as $key => $row) {
            foreach ($map as $col => $pair) {
                if (isset($row[$col]) && isset($pair[$row[$col]])) {
                    $data[$key][$col . '_text'] = $pair[$row[$col]];
                }
            }
        }
        return $data;
    }
}

//颜色 16进制转化为rgb
function hex2rgb($hexColor)
{
    $color = str_replace('#', '', $hexColor);
    if (strlen($color) > 3) {
        $rgb = array(
            'r' => hexdec(substr($color, 0, 2)),
            'g' => hexdec(substr($color, 2, 2)),
            'b' => hexdec(substr($color, 4, 2))
        );
    } else {
        $color = str_replace('#', '', $hexColor);
        $r = substr($color, 0, 1) . substr($color, 0, 1);
        $g = substr($color, 1, 1) . substr($color, 1, 1);
        $b = substr($color, 2, 1) . substr($color, 2, 1);
        $rgb = array(
            'r' => hexdec($r),
            'g' => hexdec($g),
            'b' => hexdec($b)
        );
    }
    return $rgb;
}

//颜色rgb 转 16进制
function RGBToHex($match)
{

    $hexColor = "#";
    $hex = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
    for ($i = 0; $i < 3; $i++) {
        $r = null;
        $c = $match[$i];
        $hexAr = array();
        while ($c > 16) {
            $r = $c % 16;
            $c = ($c / 16) >> 0;
            array_push($hexAr, $hex[$r]);
        }
        array_push($hexAr, $hex[$c]);
        $ret = array_reverse($hexAr);
        $item = implode('', $ret);
        $item = str_pad($item, 2, '0', STR_PAD_LEFT);
        $hexColor .= $item;
    }
    return $hexColor;
}

/** curl 获取 https 请求
 * @param String $url 请求的url
 * @param Array $data 要發送的數據
 * @param Array $header 请求时发送的header
 * @param int $timeout 超时时间，默认30s
 */
function curl_https($url, $data = array(), $header = array(), $timeout = 10000)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);

    $response = curl_exec($ch);

    if ($error = curl_error($ch)) {
        die($error);
    }

    curl_close($ch);

    return $response;

}

if (!function_exists('check_string_is_number')) {
    function check_string_is_number($string)
    {
        if (preg_match('/\d+/', $string)) {
            return true;
        } else return false;
    }
}
if (!function_exists('check_string_is_en')) {
    function check_string_is_en($string)
    {

        if (preg_match("/^[A-Za-z]+$/", $string)) {
            return true;
        } else return false;
    }
}
if (!function_exists('check_string_is_cn')) {
    function check_string_is_cn($string)
    {
        if (preg_match("/[\x7f-\xff]/", $string)){
            return true;
        } else {
            return false;
        }
    }
}

//金额转汉字大写
function cny($ns)
{
    static $cnums = array("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖");
    $cnyunits = array("圆", "角", "分");
    $grees = array("拾", "佰", "仟", "万", "拾", "佰", "仟", "亿");

    $_cny_map_unit = function ($list, $units) {
        $ul = count($units);
        $xs = array();
        foreach (array_reverse($list) as $x) {
            $l = count($xs);
            if ($x != "0" || !($l % 4)) $n = ($x == '0' ? '' : $x) . ($units[($l - 1) % $ul]);
            else $n = is_numeric($xs[0][0]) ? $x : '';
            array_unshift($xs, $n);
        }
        return $xs;
    };

    list($ns1, $ns2) = explode(".", $ns, 2);
    $ns2 = array_filter(array($ns2[1], $ns2[0]));
    $ret = array_merge($ns2, array(implode("", $_cny_map_unit(str_split($ns1), $grees)), ""));
    $ret = implode("", array_reverse($_cny_map_unit($ret, $cnyunits)));
    return str_replace(array_keys($cnums), $cnums, $ret);
}

/**
 *数字金额转换成中文大写金额的函数
 *String Int  $num  要转换的小写数字或小写字符串
 *return 大写字母
 *小数位为两位
 **/
function get_amount($num)
{
    $c1 = "零壹贰叁肆伍陆柒捌玖";
    $c2 = "分角元拾佰仟万拾佰仟亿";
    $num = round($num, 2);
    $num = $num * 100;
    if (strlen($num) > 10) {
        return "数据太长，没有这么大的钱吧，检查下";
    }
    $i = 0;
    $c = "";
    while (1) {
        if ($i == 0) {
            $n = substr($num, strlen($num) - 1, 1);
        } else {
            $n = $num % 10;
        }
        $p1 = substr($c1, 3 * $n, 3);
        $p2 = substr($c2, 3 * $i, 3);
        if ($n != '0' || ($n == '0' && ($p2 == '亿' || $p2 == '万' || $p2 == '元'))) {
            $c = $p1 . $p2 . $c;
        } else {
            $c = $p1 . $c;
        }
        $i = $i + 1;
        $num = $num / 10;
        $num = (int)$num;
        if ($num == 0) {
            break;
        }
    }
    $j = 0;
    $slen = strlen($c);
    while ($j < $slen) {
        $m = substr($c, $j, 6);
        if ($m == '零元' || $m == '零万' || $m == '零亿' || $m == '零零') {
            $left = substr($c, 0, $j);
            $right = substr($c, $j + 3);
            $c = $left . $right;
            $j = $j - 3;
            $slen = $slen - 3;
        }
        $j = $j + 3;
    }

    if (substr($c, strlen($c) - 3, 3) == '零') {
        $c = substr($c, 0, strlen($c) - 3);
    }
    if (empty($c)) {
        return "零元整";
    } else {
        return $c . "整";
    }
}


function assoc_unique($arr, $key)
{
    $tmp_arr = array();
    foreach ($arr as $k => $v) {
        if (in_array($v[$key], $tmp_arr)) {//搜索$v[$key]是否在$tmp_arr数组中存在，若存在返回true
            unset($arr[$k]);
        } else {
            $tmp_arr[] = $v[$key];
        }
    }
    sort($arr); //sort函数对数组进行排序
    return $arr;
}


function array_unique_fb($array2D)
{
    foreach ($array2D as $v) {
        $v = join(",", $v); //降维,也可以用implode,将一维数组转换为用逗号连接的字符串
        $temp[] = $v;
    }
    $temp = array_unique($temp);//去掉重复的字符串,也就是重复的一维数组
    foreach ($temp as $k => $v) {
        $temp[$k] = explode(",", $v);//再将拆开的数组重新组装
    }
    return $temp;
}
//$arr->传入数组   $key->判断的key值
function array_unset_tt($arr,$key){
    //建立一个目标数组
    $res = array();
    foreach ($arr as $value) {
        //查看有没有重复项
        if(isset($res[$value[$key]])){
            unset($value[$key]);  //有：销毁
        }else{
            $res[$value[$key]] = $value;
        }
    }
    return $res;
}



function getExt($url)
{
    $urlinfo = parse_url($url);
    $file = basename($urlinfo['path']);
    if (strpos($file, '.') !== false) {
        $ext = explode('.', $file);
        return $ext[count($ext) - 1];
    }
    return 'no extension';
}





